package cn.vihub.filter;

import cn.vihub.utils.Result;
import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.http.Header;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;

import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


/**
 * @Author: 秋晚
 * @Date: 2025/8/6 18:56
 * @Description:
 **/
@Configuration
public class MyFilter implements GlobalFilter {

    @Value("${mygateway.role.path}")
    private String rolePath;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取当前路径
        String path = request.getPath().toString();
        String[] rolePaths = this.rolePath.split(",");
        //遍历判断是否是白名单
        for (String rolePath : rolePaths) {
            boolean contains = path.contains(rolePath);
            if(contains){
                //满足条件就放行白名单
                return chain.filter(exchange);
            }
        }

        //获取token
        String token = request.getHeaders().getFirst("X-client-token");
        if(token==null){
            //token不存在情况
            return outputJson(response,"token不能为null!");
        }

        //解密token
        try {
            Claims body = Jwts.parser().setSigningKey("128903djsjhduihas167645").parseClaimsJws(token)
                    .getBody();
            //判断接口的来源
            String first = request.getHeaders().getFirst("X-Client-id");
            if(first==null){
                return outputJson(response,"请求来源不能为空!");
            }
            ServerHttpRequest httpRequest=null;
            if("admin".equals(first)){
                Integer userId = body.get("userId", Integer.class);
                httpRequest = exchange.getRequest().mutate().header("X-User-Id", userId.toString()).build();
            }else if("app".equals(first)){
                Integer memberId = body.get("userId", Integer.class);
                httpRequest =exchange.getRequest().mutate().header("X-Member-Id",memberId.toString()).build();
            }

            assert httpRequest!=null;
            //构建将userId包在请求头中  方便其他微服务调用
            ServerWebExchange serverWebExchange = exchange.mutate().request(httpRequest).build();

            return chain.filter(serverWebExchange);
        }catch (Exception e){
            return outputJson(response,e.getMessage());
        }
    }

    private Mono<Void> outputJson(ServerHttpResponse response,String msg){
        //设置200的返回状态码
        response.setStatusCode(HttpStatus.OK);
        //设置返回头
        response.getHeaders().set("Content-Type","tapplication/\\json");
        //设置返回内容
        Result<Object> objectResult = new Result<>(-1,msg,"~~~HaHaHa~~~");
        //把数据内容转成Json格式  并构建一个buffer对象
        DataBuffer wrap = response.bufferFactory().wrap(JSON.toJSONBytes(objectResult));

        return response.writeWith(Mono.just(wrap));


    }
}
